<template>
  <el-dialog :title="!dataForm.id ? '新增' : (flage === 1 ? '查看': '修改')" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
      <el-form-item label="商品名称" prop="productName">
        <el-input v-model="dataForm.productName" placeholder="参数名"></el-input>
      </el-form-item>
      <el-form-item label="商品编号" prop="productSn">
        <el-input v-model="dataForm.productSn" placeholder="参数值"></el-input>
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId">
        <el-select v-model="dataForm.categoryId" @change="change()">
          <el-option :value="0" label="请选择"></el-option>
          <el-option v-for="item in categoryList" :label="item.categoryName" :key="item.id" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="商品规格">
        <el-select v-model="attributeSleclear" @change="selectChanged($event)" multiple value-key="id">
          <el-option v-for="item in attributeSle" :label="item.attributeName" :key="item.id" :value="item"></el-option>
        </el-select>
      </el-form-item> -->
      <!-- 修改时的下拉选项 -->
      <el-form-item v-if="this.dataForm.id" label="商品规格" key="el-form-item1">

        <el-select disabled :value="attributeList.map(e=>e.attributeName)" @change="selectChanged($event)" multiple
          value-key="id">
          <el-option v-for="(item,index) in attributeSle" :label="item.attributeName" :key="index" :value="item"></el-option>
        </el-select>
      </el-form-item>


      <!-- 新增时的下拉选项 -->
      <el-form-item v-else label="商品规格" key="el-form-item2">
        <el-select v-model="attributeList" @change="selectChanged($event)" multiple value-key="id">
          <el-option v-for="(item,index) in attributeSle" :label="item.attributeName" :key="index" :value="item"></el-option>
        </el-select>
      </el-form-item>



      <el-card class="box-card" style="width:94%;margin:0 auto;">
        <span class="clear">商品规格：</span>
        <div class="dadiv">
          <el-card class="box-card2">
            <!--<span class="yanse">颜色</span>-->
            <!--<div style="display: flex; flex-wrap: wrap " class="box-card2-div">

              <el-checkbox v-for="item in dataForm.skuList" :label="item.id" :key="item.id" v-model="item.showFlag"
                @change="change">{{item.productSkuName}}</el-checkbox>
            </div>-->

            <div v-for="(attributeListItems, itemsIndex) in attributeList" class="product-list-add-update">
              <div class="rong">{{attributeListItems.attributeName}}</div>


              <div class="canshu" v-for="items in attributeListItems.list">
                <el-checkbox label="items" disabled checked>{{items}}</el-checkbox>
              </div>
              <!-- <el-checkbox-group v-model="attributeListItems[index]" @change="checkboxChange($event)">
                    <el-checkbox  :label="items" :disabled="checkdisabled">{{items}}</el-checkbox>
                </el-checkbox-group> -->
              <!-- <el-checkbox-group v-model="attributeListItems.list" v-for="(items, index) in attributeListItems.list"
                  :key="index"> -->
              <!-- <el-checkbox-group class="list_add_update_group" v-model="checkedCities[itemsIndex]" v-for="(items, index) in attributeListItems.list"
                  :key="index" @change="checkboxChange(attributeList ,attributeListItems.id ,checkedCities[itemsIndex], checkedCities)">
                  <el-checkbox :label="items" :key="index" :disabled="checkdisabled" checked>
                    {{items}}</el-checkbox>
                </el-checkbox-group> -->

            </div>



            <!--<span class="rong">容量</span>
            <div class="canshu">
              <el-checkbox label="16GB"></el-checkbox>
              <el-checkbox label="32GB"></el-checkbox>
              <el-checkbox label="64GB"></el-checkbox>
              <el-checkbox label="128GB"></el-checkbox>
            </div>-->
          </el-card>


          <!-- 修改和查看的表格数据 -->
          <!-- 订单列表数据 -->
          <el-table v-if="this.dataForm.id" :data="dataForm.skuList" key="1" border stripe>
            <el-table-column type="index"></el-table-column>
            <el-table-column v-for="(item, index) in attributeList" :key="index" :label="item.attributeName">
              <template slot-scope="scope">
                {{getColumnValue(scope.row.id, item.attributeId)}}
              </template>
            </el-table-column>
            <el-table-column label="编码" prop="productSkuSn"></el-table-column>
            <el-table-column label="售价" visEdit="true">
              <template slot-scope="scope">
                <el-input prop="unitPrice" v-model.number="scope.row.unitPrice"></el-input>
              </template>
            </el-table-column>
          </el-table>

          <!-- 新增时的表格 -->
          <el-table v-else :data="dataForm.skuList" border stripe key="2">
            <el-table-column type="index"></el-table-column>
            <el-table-column v-for="(item, index) in attributeList" :key="index" :label="item.attributeName">
              <template slot-scope="scope">
                <!-- {{getColumnValuedemo(scope.row) [item.attributeName] }} -->
                {{scope.row.attrEntities[item.attributeName].name}}
                <!-- {{scope.row.attrEntities[]}} -->
                <!-- {{getColumnValuedemo(scope.row, item.attributeName) }} -->
              </template>
            </el-table-column>

            <el-table-column label="售价" visEdit="true">
              <template slot-scope="scope">
                <el-input prop="unitPrice" v-model.number="scope.row.unitPrice"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button v-if="flage !== 1" type="primary" @click="dataFormSubmit()" :disabled="isdisabled">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data() {
      return {
        checkedCities: [],
        tableList: [],
        visible: false,
        dataForm: {
          productName: '',
          productSn: '',
          productImage: '',
          unitPrice: '',
          minPrice: '',
          skuList: [
            {
              attrEntities: [
                {
                  attrKey: "",
                  attrValue: "",
                  id: 0
                }
              ],
              costPrice: 0,
              createId: 0,
              createTime: '',
              deleteFlag: true,
              id: 0,
              marketPrice: 0,
              productId: 0,
              productSkuImage: '',
              productSkuName: '',
              productSkuSn: '',
              showFlag: true,
              totalNum: 0,
              unitPrice: 0,
              updateId: 0,
              updateTime: '',
              volume: 0,
              weight: 0
            }
          ],
          categoryId: 0,
        },
        flage: 0, // 标识修改还是查看
        attributeList: [], // 用来前端展示规格属性的
        categoryList: [],
        attributeSle: [],
        attributeSleclear: [],
        checkSkuList: [], // 下拉框选择的规格属性2维数组
        checked: true,
        isdisabled: false, // 确定按钮是否可以可用
        checkdisabled: true, // 多选按钮是否可用
        updataObj: [], // 下拉被克隆对象，用来渲染表格数据
        dataRule: {
          paramKey: [
            { required: true, message: '参数名不能为空', trigger: 'blur' }
          ],
          paramValue: [
            { required: true, message: '参数值不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    created() {

    },
    methods: {
      getCategoryList() {
        this.$http({
          url: this.$http.adornUrl('/product/category/list'),
          method: 'get'
        }).then(({ data }) => {
          if (data && data.status === 200) {
            this.categoryList = data.data.list
          } else {
            this.$message.error(data.message)
          }
        })
      },
      init(id, flage) {
        this.dataForm.id = id
        this.flage = flage
        this.visible = true
        this.getCategoryList()// 获取分类下拉
        this.getAttribute() // 获取属性规格下拉
        this.$nextTick(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl('/product/get/' + id),
              method: 'get'
            }).then(({ data }) => {
              if (data && data.status === 200) {
                let obj = data.data
                this.dataForm.productName = obj.productName
                this.dataForm.productSn = obj.productSn
                this.dataForm.productImage = obj.productImage
                this.dataForm.unitPrice = obj.unitPrice
                this.dataForm.skuList = obj.skuList
                this.attributeList = obj.attributeList
                this.dataForm.attrEntities = obj.attrEntities
                this.dataForm.categoryId = obj.categoryId
              } else {
                this.$message.error(data.message)
              }
            })
          } else {
            this.initFormData();
            this.checkdisabled = false; // 多选按钮可用
            this.attributeList = [];
            this.$refs['dataForm'].resetFields();
          }
        })

      },
      // 表单提交
      dataFormSubmit() {
        this.isdisabled = true;
        this.$refs['dataForm'].validate(valid => {
          // 新增时数据处理

          if (!this.dataForm.id) {
            let attrEntitiesItem = this.dataForm.skuList.map(e => Object.keys(e.attrEntities).map((el) =>
              ({ "attrKey": [el][0], "attrValue": e.attrEntities[el].name, "id": e.attrEntities[el].id })));
            this.dataForm.skuList.forEach((item, index) => {
              item.attrEntities = attrEntitiesItem[index];
            })
          }
          


          if (valid) {
            this.$http({
              url: this.$http.adornUrl(
                `/product/${
                !this.dataForm.id ? 'save' : 'update/' + this.dataForm.id
                }`
              ),
              method: 'post',
              data: this.$http.adornData({
                id: this.dataForm.id || undefined,
                categoryList: this.dataForm.categoryList,
                productName: this.dataForm.productName,
                productSn: this.dataForm.productSn,
                categoryId: this.dataForm.categoryId,
                skuList: this.dataForm.skuList,
              })
            }).then(({ data }) => {
              if (data && data.status === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.message)
              }
              this.isdisabled = false;
            })
          }
        })
      },
      change() {
        // 刷新form表单
        this.$forceUpdate()
      },
      selectChanged(item) {  // 下拉框选择之后item就是数据

        this.attributeList = [];
        this.attributeList.push(...item)

        this.attributeList.map((item, index) => {
          this.checkedCities[index] = []; //  创建二维数组
        })

        this.updataObj = JSON.parse(JSON.stringify(this.attributeList)); // 下拉选择克隆对象
        let attrEntitiesObj = {}
        this.initTable(item);
        // console.log(this.dataForm.skuList);
        // console.log(  this.dataForm.skuList.map(e => Object.keys(e.attrEntities).map((el) =>
        //       ({ "arrKey": [el][0], "attrValue": e.attrEntities[el].name, "id": e.attrEntities[el].id }))));



        // 当后台返回的数据需要处理成一下格式给列表渲染
        // let demo = this.dataForm.skuList.map(e => Object.keys(e.attrEntities).map((el) =>
        //   ({ "arrKey": [el][0], "attrValue": e.attrEntities[el].name, "id": e.attrEntities[el].id })));
        // let demoarr = [];
        // console.log(demo.map((e, index) => e.map((el, index) => 
        // ({ [el.arrKey]: { "name": el.attrValue, "id": el.id } }))).forEach((item, index) => {
        //   demoarr.push(item);
        // }));


        // start
        // const skusList = this.attributeList.map(e=>e.list);
        // if(item.length==0){
        //   return
        // }


        // item.forEach(item => {
        //   attrEntitiesObj[`${item.attributeName}`] = item.list
        // })

        // this.tableList =   this.j2a(attrEntitiesObj);
        // console.log(item);
        // end

        // const typeList = item.map(e => e.list.map(el => ({ [e.attributeName]: el , id: e.id })) )

        // let resArr = typeList[0];

        // for (let i = 1; i < typeList.length; i++) {
        //   let itArr = typeList[i].map(e => [e]);
        //   let tempArr = resArr;
        //   let newArr = []
        //   tempArr.forEach(el => {
        //     itArr.forEach(e => {
        //       newArr.push(e.concat(el))
        //     })
        //   })
        //   resArr = newArr;
        // }

        // this.tableList = resArr  =  resArr.map(e =>  e.reduce((a, b) => ({ ...a, ...b })) )
        // console.log(this.tableList);


        // console.log(this.tableList);
        /*this.dataForm.skuList[0].attrEntities = [];  //选择的商品规格数据
        let attrEntitiesObj

        // 进行对象转化
        item.forEach((items, index) => {
          attrEntitiesObj = {  // 目标对象
            attrKey: "",
            attrValue: "",
            id: 0
          }
          attrEntitiesObj.attrKey = items.attributeName;
          attrEntitiesObj.attrValue = items.attributeName;
          attrEntitiesObj.id = items.id;
          this.dataForm.skuList[0].attrEntities.push(attrEntitiesObj)
        })*/

      },
      initTable(item) {  // sku表格处理数据方法
        if (item.length === 0) { // 当下拉框删除全部数据之后，要将skulist清空，不然会导致表格中有数据
          this.dataForm.skuList = [];
          return
        }

        this.dataForm.skuList = [];
        // 将下拉框对象的list取出来，并且拼接成 [[{},{}],[{},{}]] 的数据格式 
        const typeList = item.map(e => e.list.map(el => ( { [e.attributeName]: { "name": el , "id": e.id } } )));
        // 获取第一项
        let resArr = typeList[0];
        // 循环最外层对象，进行矩阵循环
        for (let i = 1; i < typeList.length; i++) {
          // 
          let itArr = typeList[i].map(e => [e]);
          let tempArr = resArr;
          let newArr = []
          tempArr.forEach(el => {
            itArr.forEach(e => {
              newArr.push(e.concat(el).reduce((a, b) => ({ ...a, ...b }))  )
            })
          })
          resArr = newArr;
        }

        //this.tableList = resArr;
        //this.dataForm.skuList.attrEntities = resArr;
        //this.dataForm.skuList[index] = this.getSkulistModel(); // 创建table循环列表
        resArr.map((e, index) => { this.dataForm.skuList[index] = this.getSkulistModel(); });

        this.dataForm.skuList.map((e, index) => { e.attrEntities = resArr[index] });
        // console.log(this.dataForm.skuList.map(e => e.attrEntities.map(el => Object.keys(el).map((ell) =>
        //  ({ "arrKey": [ell][0], "attrValue": el[ell].name, "id": el[ell].id })))));
        // Object.keys(e.attrEntities).map((el) => ({ "arrKey": [el][0], "attrValue": e[el].name, "id": e[el].id }))));

      },
      checkboxChange(targetObj, index, arritems, arritemsSum) {  // 选择多选框，进行talbe动态渲染
        this.updataObj.map(e => {
          if (e.id === index) {
            e.list = arritems;
          }
        })
        //console.log(this.checkedCities[obj2].list);
        //this.selectChanged(this.updataObj);
        this.initTable(this.updataObj);
        //console.log(this.tableList.map(e => Object.keys(e).map((el) => ({ "arrKey": [el][0], "attrValue": e[el].name, "id": e[el].id }))).flat());
        //console.log(this.tableList..map(e => Object.keys(e).map((el) => ({ "arrKey": [el][0], "attrValue": e[el].name, "id": e[el].id }))));
      },
      initFormData() { // 初始化数据模型
        this.dataForm.skuList = [
          {
            attrEntities: [
              {
                attrKey: "",
                attrValue: "",
                id: 0
              }
            ],
            costPrice: 0,
            createId: 0,
            createTime: '',
            deleteFlag: true,
            id: 0,
            marketPrice: 0,
            productId: 0,
            productSkuImage: '',
            productSkuName: '',
            productSkuSn: '',
            showFlag: false,
            totalNum: 0,
            unitPrice: 0,
            updateId: 0,
            updateTime: '',
            volume: 0,
            weight: 0
          }
        ];
        this.dataForm.attrEntities = [];
        this.dataForm.attributeList = [];

      },
      getColumnValue(skuId, attributeId) {
        let value = ''
        this.dataForm.attrEntities.forEach(attrEntity => {
          if (attrEntity.productSkuId === skuId && attrEntity.attributeId === attributeId) {
            value = attrEntity.attributeValue
          }
        })
        return value
      },
      getAttribute() { // 获取规格属性
        this.$http({
          url: this.$http.adornUrl('/attribute/list'),
          params: this.$http.adornParams({
            limit: 10000
          }),
          method: 'get'

        }).then(({ data }) => {
          if (data && data.status === 200) {
            this.attributeSle = data.data.list
          } else {
            this.attributeSle = []
          }
        })
      },
      getSkulistModel() {
        return {
          attrEntities: [
            {
              attrKey: "",
              attrValue: "",
              id: 0
            }
          ],
          costPrice: 0,
          createId: 0,
          createTime: '',
          deleteFlag: true,
          id: 0,
          marketPrice: 0,
          productId: 0,
          productSkuImage: '',
          productSkuName: '',
          productSkuSn: '',
          showFlag: true,
          totalNum: 0,
          unitPrice: 0,
          updateId: 0,
          updateTime: '',
          volume: 0,
          weight: 0
        }
      },

    },

    filters: {

    }
  }
</script>
<style>
  /* .el-card__body {
  width: 100%;
} */
  .el-card {
    border: 0px;
    /* float: left; */
    /* margin-left: 200px; */
  }

  .btn {
    margin-top: 10px;
  }

  .input {
    width: 150px;
    margin-top: 10px;
    margin-bottom: 10px;
  }

  .el-card__header {
    border-bottom: 0px;
  }

  .canshu {
    margin-top: 25px;
    flex: 1;
  }


  .yanse {
    display: block;
    margin-bottom: 20px;
  }

  .dadiv {
    margin-left: 80px;
  }

  .clear {
    /* display: block; */
    /* float: left; */

    margin-left: 8px;
  }

  .box-card2 {
    background-color: #f8f9fc;
    border-radius: 20px;
  }


  .el-table--border {
    margin-top: 20px;
  }

  .rong {
    display: block;
    margin-left: -5px;
    font-size: 15px
  }

  .product-list-add-update {
    display: flex;
    flex-wrap: wrap;
    margin-top: 15px
  }

  .product-list-add-update>.canshu {
    display: flex;
  }

  .product-list-add-update>.canshu>div {
    flex: 1;
  }

  .product-list-add-update:first-of-type {
    margin-top: 0px;
  }
</style>